/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function sortedListToBST(head: ListNode | null): TreeNode | null {
    if(!head){
        return null;
    }
    if(!head.next){
        return new TreeNode(head.val);
    }
    let slow: ListNode | null = head,fast: ListNode | null = head.next;
    while(fast && fast.next && fast.next.next){
        fast = fast.next.next;
        slow = slow.next;
    }
    let m: ListNode = slow.next;
    let node: TreeNode = new TreeNode(m.val);
    slow.next = null;
    node.left = sortedListToBST(head);
    node.right = sortedListToBST(m.next);
    return node;
};


// 执行用时：
// 84 ms
// , 在所有 TypeScript 提交中击败了
// 100.00%
// 的用户
// 内存消耗：
// 43.1 MB
// , 在所有 TypeScript 提交中击败了
// 100.00%
// 的用户